package com.skyable.auth.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.skyable.auth.utils.IOUtil;
import com.skyable.common.constants.param.CommonParams;
import feign.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GaoYuan
 * @title: VerificationCodeFilter
 * @projectName spring-cloud-oauth2-demo
 * @description: TODO
 * @date 2021/4/1315:37
 */
@Slf4j
public class VerificationCodeFilter extends AbstractAuthenticationProcessingFilter {


    public VerificationCodeFilter(String defaultFilterProcessesUrl) {
//        super(new AntPathRequestMatcher("/login", "POST"));
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl, Request.HttpMethod.POST.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String code = request.getParameter(CommonParams.CODE);
        String phone = request.getParameter(CommonParams.PHONE);

        String requestBody = IOUtil.getRequestBody(request);
        try {
            JSONObject requestBodyObj = JSONObject.parseObject(requestBody);
            if(code == null || code.isEmpty()) {
                code = requestBodyObj.getString(CommonParams.CODE);
            }
            if(phone == null || phone.isEmpty()) {
                phone = requestBodyObj.getString(CommonParams.PHONE);
            }
        } catch (Exception e) {
            log.error("parse request body content error");
        }

        if(code != null && phone != null) {
            // 生成验证 authenticationToken
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(phone, code);
            // 返回验证结果
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return null;
    }
}
